package com.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.dao.TimelineDAO;
import com.model.Timeline;
import com.util.Page;

@Repository
public class TimelineDAOImpl implements TimelineDAO {
	@Autowired
	private SessionFactory sessionFactory;

	public void addEvent(Timeline event) {
		sessionFactory.getCurrentSession().save(event);
	}

	public void deleteEvent(int userId, String action, int targetId) {
		Session s = sessionFactory.getCurrentSession();
		String sql = "delete from timeline where user_id=:userId and action=:action and target_id=:targetId";
		
		Query query = s.createSQLQuery(sql);
		query.setInteger("userId", userId);
		query.setInteger("targetId", targetId);
		query.setString("action", action);
		query.executeUpdate();
	}

	public List<Timeline> getEventPageByUserId(String userIds, long lasttime, int pageSize) {
		try {
			Session s = sessionFactory.getCurrentSession();
			String hql = "";
			Query query = null;
			if(lasttime==0){
				hql = "select t from Timeline t where t.user.id in (" + userIds
					+ ") and t.isPublic=1 and (t.action='article' or t.action='question' or t.action='answer') order by t.createAt desc";
				query = s.createQuery(hql);
			}else{
				hql = "select t from Timeline t where t.user.id in (" + userIds
						+ ") and t.isPublic=1 and t.createAt<:lasttime and (t.action='article' or t.action='question' or t.action='answer') order by t.createAt desc";
				query = s.createQuery(hql);
				query.setTimestamp("lasttime", new Date(lasttime));
			}

			query.setMaxResults(pageSize);
			return query.list();
		}
		catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return null;
	}

	public Page findCollectEventPageByUserId(int userId, int page,
			int pageSize) {
		Session s = sessionFactory.getCurrentSession();
		String hql = "select t from Timeline t where t.user.id=:userId and t.action like 'collect-%' order by t.createAt desc";
		String sqlc = "select count(*) from timeline t where t.user_id=:userId and t.action like 'collect-%'";
		
		Query query = s.createQuery(hql);
		Query queryc = s.createSQLQuery(sqlc);
		
		query.setInteger("userId", userId);
		queryc.setInteger("userId", userId);
		
		query.setMaxResults(pageSize);
		query.setFirstResult((page-1)*pageSize);
		
		int count = Integer.parseInt((queryc.uniqueResult().toString()));
		Page pageIns = new Page(count,pageSize,page);
		pageIns.setList(query.list());
		return pageIns;
	}

}
